<?php
class LoginForm extends CFormModel{

	public $username;
	public $remmember;
	public $password;
	public $verify;
	public $login_ip;
	private $_identity;

	/**
 * 验证规则
 * @return array 验证规则数组
 */
	public function rules(){
		return array(
			array('username', 'required', 'message'=>'用户名不能为空'),
			array('password', 'required', 'message'=>'密码不能为空'),
			array('verify', 'captcha', 'message'=>'验证码不正确'),
			array('remmember', 'boolean'),
			array('password', 'checkUser')
			);
	}

	/**
 * 登录验证方法
 * @param  string $attribute 要验证的属性
 * @param  string $params    规则中定义的参数
 */
	public function checkUser($attribute,$params)  
	{
		if(!$this->hasErrors()){
		    $this->_identity=new UserIdentity($this->username,$this->password);  
		    if(!$this->_identity->authenticate()){
		        $this->addError('password','用户名或密码错误');		//添加错误 
		    }
		}
	}  
	  
	/** 
	 * Logs in the user using the given username and password in the model. 
	 * @return boolean whether login is successful 
	 */  
	public function login()  
	{  
	    if($this->_identity===null)  
	    {  
	        $this->_identity=new UserIdentity($this->username,$this->password);
	        $this->_identity->authenticate();  
	    }  
	    if($this->_identity->errorCode===UserIdentity::ERROR_NONE)  
	    {  
	        $duration=$this->remmember ? 3600*24*30 : 0; // 30 days  
	        Yii::app()->user->login($this->_identity,$duration);  
	        return true;  
	    }  
	    else  
	        return false;  
	}  
}